<template>
  <div class="charge-card-manage">
    <div class="page-header">
      <i class="el-icon-credit-card"></i>
      <span>充电卡管理</span>
    </div>

    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="请输入充电卡编号/客户姓名/手机号进行搜索"
        class="search-input"
        clearable
        prefix-icon="el-icon-search"
        @clear="handleSearch"
        @keyup.enter.native="handleSearch"
      >
      </el-input>
      <div class="button-group">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="handleSearch">查询</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete" :disabled="!selectedRows.length">删除</el-button>
      </div>
    </div>

    <el-table
      :data="tableData"
      border
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="序号" width="80" align="center"></el-table-column>
      <el-table-column prop="cardNumber" label="充电卡编号" min-width="140" align="center"></el-table-column>
      <el-table-column prop="customerName" label="目标客户" min-width="120" align="center"></el-table-column>
      <el-table-column prop="phoneNumber" label="联系电话" min-width="120" align="center"></el-table-column>
      <el-table-column prop="idCardNumber" label="身份证号码" min-width="180" align="center"></el-table-column>
      <el-table-column prop="membershipLevel" label="会员等级" min-width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="getMemberLevelType(scope.row.membershipLevel)">VIP{{ scope.row.membershipLevel }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="openCardTime" label="开卡时间" min-width="160" align="center"></el-table-column>
      <el-table-column prop="cardBalance" label="卡内余额" min-width="100" align="center">
        <template slot-scope="scope">
          ¥ {{ scope.row.cardBalance }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" min-width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="180" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            type="text" 
            size="small" 
            :style="{ color: scope.row.status === 2 ? '#F56C6C' : '#409EFF' }"
            @click="handleDisable(scope.row)"
          >
            {{ scope.row.status === 2 ? '启用' : '禁用' }}
          </el-button>
          <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 新增充电卡弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :before-close="handleDialogClose"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="卡号" prop="cardNumber">
          <el-input v-model="formData.cardNumber" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="客户ID" prop="customerId">
          <el-input v-model="formData.customerId" disabled></el-input>
        </el-form-item>

        <el-form-item label="开卡时间" prop="openCardTime">
          <el-input v-model="formData.openCardTime" disabled></el-input>
        </el-form-item>

        <el-form-item label="卡内余额" prop="cardBalance">
          <el-input-number 
            v-model="formData.cardBalance" 
            :precision="2" 
            :step="10"
            :min="0"
            controls-position="right"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="会员等级" prop="membershipLevel">
          <el-select v-model="formData.membershipLevel" placeholder="请选择会员等级">
            <el-option label="普通会员" :value="1"></el-option>
            <el-option label="白银会员" :value="2"></el-option>
            <el-option label="黄金会员" :value="3"></el-option>
            <el-option label="铂金会员" :value="4"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="remarks">
          <el-input
            type="textarea"
            :rows="3"
            v-model="formData.remarks"
            placeholder="请输入备注信息">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handleDialogClose">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ChargeCardManage',
  data() {
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号码'));
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'));
      } else {
        callback();
      }
    };
    // 身份证号验证规则
    const validateIdCard = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入身份证号码'));
      } else if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
        callback(new Error('请输入正确的身份证号码'));
      } else {
        callback();
      }
    };

    return {
      searchQuery: '',
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      selectedRows: [],
      loading: false,
      dialogVisible: false,
      dialogTitle: '',
      submitLoading: false,
      customerOptions: [], // 客户选项列表
      customerLoading: false, // 客户搜索加载状态
      formData: {
        id: null,
        cardNumber: '',
        customerId: null,
        openCardTime: '',
        cardBalance: 0,
        membershipLevel: 1,
        status: 1,
        remarks: ''
      },
      formRules: {
        cardBalance: [
          { required: true, message: '请输入卡内余额', trigger: 'blur' }
        ],
        membershipLevel: [
          { required: true, message: '请选择会员等级', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    getMemberLevelType(level) {
      const types = {
        1: 'warning',
        2: 'success',
        3: 'danger'
      }
      return types[level] || 'info'
    },
    handleSearch() {
      this.loading = true;
      this.$axios.get('/api/chargingCard/queryCard', {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchQuery ? this.searchQuery.trim() : null,
          exact: false  // 添加模糊匹配参数
        }
      })
      .then(response => {
        if (response.data.code === 200) {
          this.tableData = response.data.data;
          this.total = response.data.data.length;
          
          // 如果搜索有结果但没有数据
          if (this.searchQuery && this.tableData.length === 0) {
            this.$message.warning('未找到匹配的充电卡记录');
          }
        } else {
          this.$message.error(response.data.msg || '查询失败');
        }
      })
      .catch(error => {
        console.error('查询失败:', error);
        this.$message.error('查询失败，请稍后重试');
      })
      .finally(() => {
        this.loading = false;
      });
    },
    handleAdd() {
      this.dialogTitle = '新增充电卡';
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.resetFields();
        this.loadCustomerList();
        this.generateCardNumber(); // 生成充电卡编号
      });
    },
    handleView(row) {
      this.$message.info('查看充电记录详情功能开发中');
    },
    handleEdit(row) {
      this.dialogTitle = '编辑充电卡';
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.formData = { ...row };
      });
    },
    handleDelete(row) {
      this.$confirm('确认删除该充电卡吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        this.$axios.delete(`/api/chargingCard/${row.id}`)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('删除成功');
              this.handleSearch(); // 刷新列表
            } else {
              this.$message.error(response.data.msg || '删除失败');
            }
          })
          .catch(error => {
            console.error('删除失败:', error);
            this.$message.error('删除失败，请稍后重试');
          })
          .finally(() => {
            this.loading = false;
          });
      }).catch(() => {
        // 取消删除，不做任何操作
      });
    },
    handleBatchDelete() {
      if (!this.selectedRows.length) return;
      
      this.$confirm(`确认删除选中的 ${this.selectedRows.length} 条充电卡记录吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        // 创建删除请求数组
        const deletePromises = this.selectedRows.map(row => 
          this.$axios.delete(`/api/chargingCard/${row.id}`)
        );
        
        // 使用 Promise.all 处理所有删除请求
        Promise.all(deletePromises)
          .then(responses => {
            // 检查是否所有请求都成功
            const allSuccess = responses.every(response => response.data.code === 200);
            if (allSuccess) {
              this.$message.success('批量删除成功');
              this.handleSearch(); // 刷新列表
            } else {
              this.$message.warning('部分删除失败，请刷新后重试');
            }
          })
          .catch(error => {
            console.error('批量删除失败:', error);
            this.$message.error('批量删除失败，请稍后重试');
          })
          .finally(() => {
            this.loading = false;
          });
      }).catch(() => {
        // 取消删除，不做任何操作
      });
    },
    handleDisable(row) {
      const action = row.status === 2 ? '启用' : '禁用';
      this.$confirm(`确认${action}该充电卡吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const updateData = {
          ...row,
          status: row.status === 2 ? 1 : 2  // 在 1 和 2 之间切换
        };
        
        this.$axios.post('/api/chargingCard/update', updateData)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success(`${action}成功`);
              this.handleSearch();
            } else {
              this.$message.error(response.data.msg || `${action}失败`);
            }
          })
          .catch(error => {
            console.error(`${action}充电卡失败:`, error);
            this.$message.error(`${action}失败，请稍后重试`);
          });
      }).catch(() => {});
    },
    getStatusText(status) {
      switch (status) {
        case 1:
          return '正常';
        case 2:
          return '禁用';
        default:
          return '未知';
      }
    },
    getStatusType(status) {
      switch (status) {
        case 1:
          return 'success';
        case 2:
          return 'danger';
        default:
          return 'info';
      }
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.handleSearch();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handleSearch();
    },
    handleDialogClose() {
      this.$refs.formRef.resetFields();
      this.formData = {
        id: null,
        cardNumber: '',
        customerId: null,
        openCardTime: '',
        cardBalance: 0,
        membershipLevel: 1,
        status: 1,
        remarks: ''
      };
      this.dialogVisible = false;
    },
    handleSubmit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          const isEdit = this.formData.id !== null;
          const api = isEdit ? '/api/chargingCard/update' : '/api/charging-card/add';
          
          this.submitLoading = true;
          this.$axios.post(api, this.formData)
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success(isEdit ? '修改成功' : '添加成功');
                this.dialogVisible = false;
                this.handleSearch();
              } else {
                this.$message.error(response.data.msg || (isEdit ? '修改失败' : '添加失败'));
              }
            })
            .catch(error => {
              console.error(isEdit ? '修改充电卡失败:' : '添加充电卡失败:', error);
              this.$message.error(isEdit ? '修改失败，请稍后重试' : '添加失败，请稍后重试');
            })
            .finally(() => {
              this.submitLoading = false;
            });
        }
      });
    },
    // 新增加载客户列表的方法
    loadCustomerList() {
      this.customerLoading = true;
      this.$axios.get('/api/customer/list', {
        params: {
          pageNum: 1,
          pageSize: 100  // 获取较多数据以供选择
        }
      })
      .then(response => {
        if (response.data.code === 200) {
          this.customerOptions = response.data.data;
        } else {
          this.$message.error(response.data.msg || '获取客户列表失败');
        }
      })
      .catch(error => {
        console.error('获取客户列表失败:', error);
        this.$message.error('获取客户列表失败，请稍后重试');
      })
      .finally(() => {
        this.customerLoading = false;
      });
    },
    // 客户选择变更处理
    handleCustomerChange(customerId) {
      const selectedCustomer = this.customerOptions.find(item => item.id === customerId);
      if (selectedCustomer) {
        this.formData.customerId = selectedCustomer.id;
        this.formData.customerName = selectedCustomer.customerName;
        this.formData.phoneNumber = selectedCustomer.phoneNumber;
        this.formData.idCardNumber = selectedCustomer.idCardNumber;
      }
    },
    // 生成充电卡编号
    generateCardNumber() {
      // 生成充电卡编号规则：CC + 年份后两位 + 8位随机数
      const date = new Date();
      const year = date.getFullYear().toString().slice(-2); // 获取年份后两位
      const random = Math.floor(Math.random() * 100000000).toString().padStart(8, '0'); // 生成8位随机数
      const cardNumber = `CC${year}${random}`;
      this.formData.cardNumber = cardNumber;
    },
  },
  created() {
    this.handleSearch();
  }
}
</script>

<style scoped>
.charge-card-manage {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.page-header i {
  font-size: 24px;
  margin-right: 10px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.search-input :deep(.el-input__inner) {
  border-radius: 20px;
}

.search-input :deep(.el-input__prefix) {
  left: 10px;
}

.search-input :deep(.el-input__inner) {
  padding-left: 35px;
}

.button-group {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  margin-top: 15px;
}

:deep(.el-button--text) {
  padding: 0 8px;
}

:deep(.el-button--text + .el-button--text) {
  margin-left: 0;
}

:deep(.el-tag) {
  text-transform: uppercase;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: bold;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-select-dropdown__item) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-number-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  display: block;
}

:deep(.el-input.is-disabled .el-input__inner) {
  color: #606266;
  background-color: #f5f7fa;
}
</style>
